import { createRouter, createWebHistory } from 'vue-router';

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        component: () => import('../components/LoginView.vue')
    },
    {
        path: '/home',
        name: 'HomeDemo',
        component: () => import('../views/HomeDemo.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/about',
        name: 'AboutDemo',
        component: () => import('../views/AboutDemo.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/studentList',
        name: 'StudentList',
        component: () => import('../components/StudentList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/courseList',
        name: 'CourseList',
        component: () => import('../components/CourseList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/classList',
        name: 'ClassList',
        component: () => import('../components/ClassList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/studentCourseList',
        name: 'StudentCourseList',
        component: () => import('../components/StudentCourseList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/dbManagementList',
        name: 'DbManagementList',
        component: () => import('../components/DbManagementList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/oaMessageList',
        name: 'OaMessageList',
        component: () => import('../components/OaMessageList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/systemUserList',
        name: 'SystemUserList',
        component: () => import('../components/SystemUserList.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/contact',
        name: 'ContactDemo',
        component: () => import('../views/ContactDemo.vue'),
        meta: { requiresAuth: true }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const isLoggedIn = localStorage.getItem('userToken') !== null;

    if (requiresAuth && !isLoggedIn) {
        next('/login'); // 如果需要认证且未登录，重定向到登录页面
    } else {
        next(); // 否则继续导航
    }
});

export default router;